<link rel="stylesheet" href="/assets/adai/css/template_index.css" media="all">
<script type="text/javascript" src="/assets/lib/color/color.js"></script>
<div class="layui-fluid template_page">
    <div class="layui-tab" lay-filter="generator_template_tab">
        <ul class="layui-tab-title">
            <li class="layui-this">本地模板库</li>
            <li>官方模板库</li>
        </ul>
        <div class="layui-tab-content">
            <div class="layui-tab-item layui-show">
                <div class="layui-card">
                    <!-- 搜索表单区 -->
                    <form class="layui-form layui-card-header layuiadmin-card-header-auto" lay-filter="template_model-search-form">
                        <div class="layui-form-item">


                            <!-- 默认表单 -->
                            <div class="layui-inline">
                                <label class="layui-form-label">模板名称</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="template_name__op__like" placeholder="请输入模板名称" autocomplete="off" class="layui-input">
                                </div>
                            </div>


                            <!-- 默认表单 -->
                            <div class="layui-inline">
                                <label class="layui-form-label">需要表数</label>
                                <div class="layui-input-inline">
                                    <input type="number" name="table_require_count" placeholder="请输入需要表数" autocomplete="off" class="layui-input">
                                </div>
                            </div>


                            <div class="layui-inline">
                                <button class="layui-btn btn-template_model-search" lay-submit lay-filter="btn-template_model-form-search">
                                    <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>
                                </button>
                                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                            </div>
                        </div>
                    </form>
                    <!-- 列表区 -->
                    <div class="layui-card-body">
                        <div class=" layui-btn-group oper-btns">
                            <buttom class="layui-btn add-btn"><i class="layui-icon layui-icon-add-1"></i>新建</buttom>
                            <buttom class="layui-btn import-btn"><i class="fa fa-upload"></i>导入</buttom>
                        </div>
                        <div class="template_list" id="code_template_list">

                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-tab-item official_tab_content">
            </div>
        </div>
    </div>
</div>
<script>
    layui.use(['table', 'form', 'layer', 'laydate', 'jquery', 'admin', 'formSelects', 'element', 'upload'], function () {
        var form = layui.form, layer = layui.layer, laydate = layui.laydate, table = layui.table, admin = layui.admin, formSelects = layui.formSelects;
        var upload = layui.upload; //得到 upload 对象
        let element = layui.element;
        let $ = layui.$;
        let officialSvg = `
            <svg t="1605870400016" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="17927" data-spm-anchor-id="a313x.7781069.0.i35" width="24" height="24"><path d="M876.16 427.2A337.6 337.6 0 1 0 544 771.52a339.2 339.2 0 0 0 332.16-344.32zM554.24 544l-142.4 96 26.56-164.8-125.44-104 162.24-32 64-136 78.08 134.4 163.2 26.88-131.52 109.12 40 154.24z m-306.56 137.28l-94.08 160 128 5.12L336.64 960l118.08-153.6a381.76 381.76 0 0 1-207.04-125.12z m596.16-17.92A381.44 381.44 0 0 1 647.04 800l122.56 149.76 51.84-112.96 126.4-8z" p-id="17928" fill="#ecdb0a"></path></svg>
        `;
        let updateSvg = `
            <svg t="1605868137731" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="11339" width="24" height="24"><path d="M512 512m-512 0a512 512 0 1 0 1024 0 512 512 0 1 0-1024 0Z" fill="#d81e06" p-id="11340"></path><path d="M766.269752 499.547728L548.420347 281.698323a43.330548 43.330548 0 0 0-61.691804 0L268.880337 499.547728c-27.535288 27.530492-8.016937 74.238801 31.020965 74.238801h99.937124v142.043429a43.584749 43.584749 0 0 0 43.572759 43.567962h148.683841a43.584749 43.584749 0 0 0 43.569161-43.569161V573.786529h99.94312c38.686576 0 57.859597-46.708309 30.669639-74.238801z" fill="#ffffff" p-id="11341" data-spm-anchor-id="a313x.7781069.0.i18" class="selected"></path></svg>
        `
        form.render(null, 'template_model-search-form');


        // 表单搜索监听
        form.on('submit(btn-template_model-form-search)', function (data) {
            var field = data.field;
            //执行重载
            renderTemplateList();
            return false;
        });


        // 添加事件
        $(".oper-btns .add-btn").click(function () {
            eventListener({event: 'add'});
        })

        function focusTemplateBlock(templateId) {
            let $block = $(`.template_list > div[tpl_id="${templateId}"]`);
            if ($block[0]) {
                $block[0].scrollIntoView();
                $block.css("box-shadow", "0px 0px 52px #1b00fb");
                setTimeout(function () {
                    $block.css("box-shadow", "");
                }, 3000);
            }
        }

        //创建一个上传组件
        upload.render({
            elem: '.oper-btns .import-btn'
            , url: '/generator/template/importTemp'
            , choose: function (obj) {
                //将每次选择的文件追加到文件队列
                var files = obj.chooseFiles;
                let $tip = $(`
                    <div class="template_import_dialog">
                        <div class="import_info_text">正在导入模板包...</div>
                        <div class="layui-progress" lay-showPercent="yes" lay-filter="template_import_progress">
                          <div class="layui-progress-bar" lay-percent="0%">
                          </div>
                        </div>
                    </div>
                `);
                $('body').append($tip);
                layui.element.render("progress", "template_import_progress");
            }
            , progress: function (n, elem, index) {
                var percent = n + '%' //获取进度百分比
                element.progress('template_import_progress', percent);
            }
            , done: function (res, index, upload) { //上传后的回调
                if (res.success) {
                    $(".template_import_dialog").remove();
                    layer.msg("导入成功！")
                    renderTemplateList(function () {
                        focusTemplateBlock(res.id);
                    })
                } else {
                    if (res && res.success && res.confirm) {
                        $(".template_import_dialog").remove();
                        let title = `官方模板【${res.templateName} v${res.newVersion}】已经存在, 确定覆盖本地模板吗？`;
                        let btnTitle = "覆盖";
                        switch (res.confirm) {
                            case "rollback":
                                title = `导入的官方模板【${res.templateName}】版本【v${res.newVersion}】低于本地版本【v${res.oldVersion}】，确定要回退版本吗？`
                                btnTitle = "回退";
                                break;
                            case "update":
                                title = `更新官方模板【${res.templateName} v${res.oldVersion} => v${res.newVersion}】吗？`
                                btnTitle = "更新";
                                break;
                        }
                        layer.msg(title, {
                            time: 0 //不自动关闭
                            , btn: [btnTitle, '取消']
                            , yes: function (index) {
                                layer.close(index);
                                $(".template_import_dialog").remove();
                                $.ajax({
                                    url: '/generator/template/importTemp',
                                    method: 'post',
                                    data: {confirm: false, unZipPath: res.path},
                                    dataType: "json",
                                    success: function (res) {
                                        if (res.success) {
                                            layer.close(layer.index);
                                            layer.msg("导入成功！");
                                            renderTemplateList(function () {
                                                focusTemplateBlock(res.id);
                                            })
                                        } else {
                                            layer.close(layer.index);
                                            layer.msg("导入失败！" + (res.message || ''));
                                        }
                                    },
                                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                                        layer.close(layer.index);
                                        layer.msg(`导入错误(${textStatus})！`, {icon: 5})
                                    },
                                    complete: function (XMLHttpRequest, textStatus) {
                                    }
                                })
                            }
                        });
                    } else {
                        $(".template_import_dialog").remove();
                        layer.msg("导入失败！" + (res.message || ''));
                    }
                }
            }
            , accept: 'file' //允许上传的文件类型
            , exts: 'zip'
            , multiple: false
            , acceptMime: "application/x-zip-compressed"
        })

        // 渲染模板列表
        function renderTemplateList(callback) {
            let data = form.val("template_model-search-form");
            data.limit = 1000;
            $.ajax({
                method: 'GET',
                url: "/generator/template/list",
                data: data,
                dataType: 'json',
                before: function () {
                },
                success: function (rs) {
                    if (rs.success) {
                        renderTemplateListData(rs);
                        callback && callback();
                    } else {
                        layer.msg('加载失败,' + rs.message || '加载失败', {icon: 5});
                    }
                },
            });
        }

        layui.renderTemplateList = renderTemplateList;
        let $svg = $(`
        <svg xmlns="http://www.w3.org/2000/svg" width="1338" height="915.47" version="1.1" >
            <g>
             <rect height="855.47" width="228" y="30" x="30" fill="#cc3314"/>
             <rect height="180" width="1020" y="30" x="288" fill="#994737"/>
             <rect height="645.47" width="1020" y="240" x="288" fill="#cc3314"/>
            </g>
        </svg>
        `);

        function renderTemplateListData(res) {
            let imgUrl = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent($svg[0].outerHTML)));
            let $tempBlock = $(`
                <div class="template_block">
                    <div class="template_preview">
                        <img src="${imgUrl}" style="width: 100%;">
                    </div>
                    <div class="template_title"></div>
                    <div class="template_opers">
                        <span class="oper_generate" title="代码生成"><i class="layui-icon layui-icon-fonts-code"></i></span>
                        <span class="oper_code_edit" title="模板文件管理"><i class="fa fa-folder"></i></span>
                        <span class="oper_setting" title="配置"><i class="layui-icon layui-icon-set"></i></span>
                        <span class="oper_copy" title="创建副本"><i class="fa fa-copy"></i></span>
                        <span class="oper_export" title="导出"><i class="fa fa-download"></i></span>
                        <span class="oper_delete" title="删除"><i class="fa fa-remove"></i></span>
                    </div>
                    <div class="template_update_icon" title="最新版本 v0.2.212，马上升级！">
                        ${updateSvg}
                    </div>
                </div>
            `);
            let list = [];
            res.data.forEach(function (item, idx) {
                let $block = $tempBlock.clone();
                $block.attr("tpl_id", item.template_id);
                if (item.official_id) {
                    $block.find(".template_official_icon").css("display", "block");
                    // $block.find(".template_update_icon").css("display", "block");
                }
                let hasThumb = false;
                if (item.thumb) {
                    let thumbs = JSON.parse(item.thumb);
                    if (thumbs.length > 0) {
                        hasThumb = true;
                        $block.find(".template_preview > img").css("width", "").attr("src", thumbs[0].file_url);
                    }
                }
                if (!hasThumb) {
                    let $cloneSvg = $svg.clone();
                    let $rects = $cloneSvg.find("rect");
                    let $rects0 = $rects.eq(0);
                    let $rects1 = $rects.eq(1);
                    let $rects2 = $rects.eq(2);
                    let color0 = net.brehaut.Color($rects0.attr("fill"));
                    let color1 = net.brehaut.Color($rects1.attr("fill"));
                    let color2 = net.brehaut.Color($rects2.attr("fill"));
                    let count = (idx % 36) + 7;
                    $rects0.attr("fill", color0.setHue(color0.getHue() + (count * (10))).toCSS());
                    $rects1.attr("fill", color1.setHue(color1.getHue() + (count * (10))).toCSS());
                    $rects2.attr("fill", color2.setHue(color2.getHue() + (count * (10))).toCSS());
                    let imgUrl = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent($cloneSvg[0].outerHTML)));
                    $block.find(".template_preview > img").css("width", "100%").attr("src", imgUrl);
                }
                let $title = $block.find(".template_title");
                $title.attr("title", (item.official_id ? '官方模板 - ' : '') + item.template_name).html((item.official_id ? officialSvg : '') + item.template_name);
                if (item.official_id) {
                    $title.css("padding", "0 10px 0 33px");//.css("color","#FFED0D");
                }
                $block.find(".oper_code_edit").on("click", function () {
                    eventListener({event: "oper_code_edit", data: item});
                    return false;
                });
                $block.find(".oper_generate").on("click", function () {
                    eventListener({event: "generate", data: item});
                    return false;
                });
                $block.find(".oper_setting").on("click", function () {
                    eventListener({event: "edit", data: item});
                    return false;
                });
                $block.find(".oper_copy").on("click", function () {
                    eventListener({event: "copy", data: item});
                    return false;
                });
                $block.find(".oper_delete").on("click", function () {
                    eventListener({event: "del", data: item});
                    return false;
                }).css("display", item.is_system ? 'none' : '');
                $block.find(".oper_export").on("click", function () {
                    eventListener({event: "export", data: item});
                    return false;
                });
                $block.find(".template_preview").attr("title", "查看详情").on('click', function () {
                    eventListener({event: "detail", data: item});
                    return false;
                });
                $block.attr("data", item);
                list.push($block);
            })
            $("#code_template_list").html('').append(list);
        }

        renderTemplateList();

        // 事件监听
        function eventListener(obj) {
            let event = obj.event;
            let data = obj.data;
            switch (event) {
                case 'add':
                    layui.$.post('/generator/template/editPage', function (str) {
                        layer.open({
                            type: 1,
                            title: '新建模板',
                            maxmin: true,
                            area: ['100%', '100%'],
                            content: str,
                        })
                    });
                    break;
                case 'edit':
                    layui.$.post('/generator/template/editPage', {template_id: data.template_id}, function (str) {
                        layer.open({
                            type: 1,
                            title: '编辑模板',
                            maxmin: true,
                            area: ['100%', '100%'],
                            content: str,
                        })
                    });
                    break;
                case 'generate':
                    layui.$.post('/generator/template/generatePage', {template_id: data.template_id}, function (str) {
                        //页面层
                        layer.open({
                            type: 1,
                            skin: 'layui-layer-rim', //加上边框
                            title: false,
                            area: ['calc(100% - 30px)', 'calc(100% - 30px)'], //宽高
                            content: str
                        });
                    });
                    break;
                case 'oper_code_edit':
                    layui.$.post('/generator/template/fileMgrPage', {template_id: data.template_id}, function (str) {
                        layer.open({
                            type: 1,
                            title: '模板文件管理',
                            maxmin: true,
                            area: ['80%', '80%'],
                            content: str,
                        })
                    });
                    break;
                case 'detail':
                    layui.$.post('/generator/template/detailPage', {template_id: data.template_id}, function (str) {
                        layer.open({
                            type: 1,
                            title: '模板详情',
                            maxmin: true,
                            area: ['100%', '100%'],
                            content: str,
                        })
                    });
                    break;
                case 'copy':
                    layui.$.post('/generator/template/copyPage', {template_id: data.template_id}, function (str) {
                        layer.open({
                            type: 1,
                            title: '创建模板副本',
                            maxmin: true,
                            area: ['600px', '170px'],
                            content: str,
                        })
                    });
                    break;
                case 'export':
                    window.open("/generator/template/export?template_id=" + data.template_id);
                    break;
                case 'dels':
                    let checkStatus = table.checkStatus('template_model-table');
                    let selectRow = checkStatus.data;
                    deleteRow(selectRow);
                    break;
                case 'del':
                    let row = obj.data;
                    deleteRow([row]);
                    break;
                case 'import':

                    break;
            }
        }

        // 删除行方法
        function deleteRow(selectRows) {
            if (selectRows.length <= 0) {
                layer.msg('请先钩选要删除的记录行！');
                return;
            }
            layer.confirm('确定要删除这' + selectRows.length + '条记录吗？',
                {icon: 3, title: '提示', btn: ['确认删除', '取消']},
                function (index) {
                    layui.$.ajax({
                        url: '/generator/template/delete',
                        data: {
                            ids: selectRows.map((row) => row.template_id)
                        },
                        traditional: true,
                        type: 'POST',
                        success: function (result) {
                            if (result.success) {
                                layer.msg(result.message, {icon: 6});
                                renderTemplateList();
                            } else {
                                layer.msg('删除失败！' + result.message, {icon: 5});
                            }
                        }
                    });
                });

        }

        element.on('tab(generator_template_tab)', function (data) {
            let $content = $(".official_tab_content", $(data.elem));
            if (!$content.find("iframe")[0]) {
                $content.html(`<iframe src="//www.jweb.cc#template" class="official_template_iframe" ></iframe>`);
                window.addEventListener('message', function (e) {
                    $('.official_template_iframe').css("height", e.data.height + 'px');
                }, false);
            }
        });

    })
</script>
